package com.Customer.controller;

import com.Customer.entity.Customer;
import com.Customer.service.CustomerService;
import com.Customer.utils.ResponseResult;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/customer")
@CrossOrigin
public class CustomerController {

    private static final Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerService customerService;

    @Value("${server.port}")
    private int serverPort;

    // 添加客户信息
    @PostMapping("/add.do")
    @CircuitBreaker(
            name = "customerService",
            fallbackMethod = "addCustomerFallback"
    )
    public ResponseResult addCustomerInfo(@RequestBody Customer customer) {
        log.info("添加客户 - 端口: {}", serverPort);
        try {
            boolean result = customerService.doAddCustomerInfo(customer);
            return ResponseResult.build(result, result ? "添加成功" : "添加失败", null);
        } catch (Exception e) {
            log.error("添加客户异常", e);
            throw e; // 让熔断机制捕获异常
        }
    }

    // 添加客户降级方法
    public ResponseResult addCustomerFallback(Customer customer, Throwable ex) {
        log.warn("熔断触发！添加客户失败 - 端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                null
        );
    }

    // 修改客户信息
    @PostMapping("/modify.do")
    @CircuitBreaker(
            name = "customerService",
            fallbackMethod = "modifyCustomerFallback"
    )
    public ResponseResult modifyCustomerInfo(@RequestBody Customer customer) {
        log.info("修改客户 - 端口: {}", serverPort);
        try {
            boolean result = customerService.doModifyCustomerInfo(customer);
            return ResponseResult.build(result, result ? "修改成功" : "修改失败", null);
        } catch (Exception e) {
            log.error("修改客户异常", e);
            throw e;
        }
    }

    // 修改客户降级方法
    public ResponseResult modifyCustomerFallback(Customer customer, Throwable ex) {
        log.warn("熔断触发！修改客户失败 - 端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                null
        );
    }

    // 删除客户信息
    @PostMapping("/delete.do")
    @CircuitBreaker(
            name = "customerService",
            fallbackMethod = "deleteCustomerFallback"
    )
    public ResponseResult deleteCustomerInfo(@RequestBody Customer customer) {
        log.info("删除客户 - 端口: {}", serverPort);
        try {
            boolean result = customerService.doDeleteCustomerInfo(customer);
            return ResponseResult.build(result, result ? "删除成功" : "删除失败", null);
        } catch (Exception e) {
            log.error("删除客户异常", e);
            throw e;
        }
    }

    // 删除客户降级方法
    public ResponseResult deleteCustomerFallback(Customer customer, Throwable ex) {
        log.warn("熔断触发！删除客户失败 - 端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                null
        );
    }

    // 获取客户信息
    @PostMapping("/get.do")
    @CircuitBreaker(
            name = "customerService",
            fallbackMethod = "getCustomerFallback"
    )
    public ResponseResult getCustomerInfo(@RequestBody Customer customer) {
        log.info("查询单个客户 - 端口: {}", serverPort);
        try {
            Customer result = customerService.doGetCustomerInfo(customer);
            return ResponseResult.build(result != null, null, result);
        } catch (Exception e) {
            log.error("查询单个客户异常", e);
            throw e;
        }
    }

    // 获取客户降级方法
    public ResponseResult getCustomerFallback(Customer customer, Throwable ex) {
        log.warn("熔断触发！查询单个客户失败 - 端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                null
        );
    }

    // 获取客户列表
    @GetMapping("/list.do")
    @CircuitBreaker(
            name = "customerService",
            fallbackMethod = "listFallback"
    )
    public ResponseResult getCustomerInfoList() {
        log.info("获取客户列表 - 端口: {}", serverPort);
        try {
            List<Customer> list = customerService.doGetCustomerInfoList();
            return ResponseResult.build(list != null, null, list);
        } catch (Exception e) {
            log.error("获取客户列表异常", e);
            throw e;
        }
    }

    // 列表降级方法
    public ResponseResult listFallback(Throwable ex) {
        log.warn("熔断触发！获取客户列表失败 - 端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                Collections.emptyList()
        );
    }

    // 查询客户列表
    @PostMapping("/query.do")
    @CircuitBreaker(
            name = "customerService",
            fallbackMethod = "queryFallback"
    )
    public ResponseResult queryCustomerInfoList(@RequestBody Customer customer) {
        log.info("条件查询客户 - 端口: {}", serverPort);
        try {
            List<Customer> list = customerService.doQueryCustomerInfoList(customer);
            return ResponseResult.build(list != null, null, list);
        } catch (Exception e) {
            log.error("条件查询客户异常", e);
            throw e;
        }
    }

    // 查询降级方法
    public ResponseResult queryFallback(Customer customer, Throwable ex) {
        log.warn("熔断触发！条件查询客户失败 - 端口: {}，异常: {}", serverPort, ex.getMessage());
        return ResponseResult.build(false,
                "服务繁忙，请稍后再试（来自端口：" + serverPort + "）",
                Collections.emptyList()
        );
    }

    // 测试熔断接口
    @GetMapping("/test-circuit-breaker")
    public ResponseResult testCircuitBreaker() {
        log.info("测试熔断 - 端口: {}", serverPort);
        try {
            List<Customer> list = customerService.doGetCustomerInfoList();
            return ResponseResult.build(true, "操作成功（端口：" + serverPort + "）", list);
        } catch (Exception e) {
            return ResponseResult.build(false, "服务暂时不可用（可能触发熔断）", null);
        }
    }
}